package conexion;

import java.sql.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DBConnectionPool {

    public static DBConnectionPool pool = new DBConnectionPool();
    protected ArrayList<ConnectionConfig> m_lstConnections = new ArrayList<ConnectionConfig>();

    /** Creates a new instance of DBConnectionPool */
    public DBConnectionPool() {
    }

    public static void setConnections(ArrayList<ConnectionConfig> lst) {
        if (pool.m_lstConnections.isEmpty()) {
            pool.m_lstConnections = lst;
        }
    }

    public static Connection getConnection(int index) {

       //  ConnectionConfig it = new ConnectionConfig();
        try {
            String host = "localhost";
            String usr = "befordo_mm";
            String psw = "mm12";
            String bd = "befordo_mm";

           // usr = "root";
            //psw  = "";

            if (pool.m_lstConnections.size() < 10)
                pool.m_lstConnections.add(new ConnectionConfig("jdbc:mysql://" + host + "/"+bd+"?useEncoding=true&characterEncoding=UTF-8", usr, psw));

             ConnectionConfig it = pool.m_lstConnections.get(index);
            if (it.m_connection == null || it.m_connection.isClosed()) {
                it.open();
            }

            return it.m_connection;
        } catch (SQLException ex) {
            Logger.getLogger(DBConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return getConnection(index);
    }

    public synchronized static ResultSet executeQuery(int index, String sql) {
        ResultSet rs = null;
        Connection c;
        try {
            c = DBConnectionPool.getConnection(index);
            Statement stm = c.createStatement();
            stm.execute("SET CHARACTER SET utf8");
            stm.execute("SET NAMES utf8");
            rs = stm.executeQuery(sql);

            c.close();
        } catch (Exception e) {
            System.out.println("Pool: " + e);
            rs = null;
        } finally {
           

        }
        return rs;
    }

    public static void close(int index) {


        ConnectionConfig it = pool.m_lstConnections.get(index);
        it.close();
    }
}